﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MvcShopping.Models;
namespace MvcShopping.Controllers
{
    public class MemberController : Controller
    {
      
        MvcShoppingContext1 db = new MvcShoppingContext1();
        //
        // GET: /Member/
        /// <summary>
        /// 会员注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 写入会员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register([Bind(Exclude="RegisterOn,AuthCode")]Member member )
        {
            var chk_member = db.Members.Where(p => p.Email 
                ==member.Email).FirstOrDefault();
            if (chk_member != null)
            {
                ModelState.AddModelError("Email", 
                    "你输入的Email已经存在");
            }
            if (ModelState.IsValid)
            {
                
                //会员注册时间
                member.RegisterOn = DateTime.Now;
                //会员验证码，采用GuID当成验证码属性
                member.AuthCode = Guid.NewGuid().ToString();
                db.Members.Add(member);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View();
            }
        }
        /// <summary>
        /// 显示会员登陆页面
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            
            return View();
        }

        /// <summary>
        /// 运行会员登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string email, string password,
            string returnUrl)
        {
            if (ValidateUser(email, password))
            {
                FormsAuthentication.SetAuthCookie(email, false);
                if (string.IsNullOrEmpty(returnUrl))
                {
                    
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    String loginuser = email;
                    String loginContent = "时间：" + DateTime.Now.ToLocalTime().ToString() + "ip:" + Request.UserHostAddress + " 登录前台";

                    Log log = new Log
                    {
                        operateName = loginuser,
                        operateContent = loginContent
                    };
                    db.Logs.Add(log);
                    db.SaveChanges();
                    return Redirect(returnUrl);
                }
            }
            ModelState.AddModelError("", "你输入的帐号或密码错误");
            return View();
        }
        private bool ValidateUser(string email, string password)
        {
            
            var member = (from p in db.Members
                          where p.Email == email &&
                          p.Password == password
                          select p).FirstOrDefault();
            return member != null;
        }

        /// <summary>
        /// 运行会员注销
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            //清除窗体验证的cookie
            FormsAuthentication.SignOut();

            //清除所有曾经写入过的Session
            Session.Clear();

            return RedirectToAction("Index", "Home");
        }

        ///
        ///找回密码
        ///
        public ActionResult findPassword()
        {

            return View();
        }
        ///找回密码实现
        public ActionResult findVadify()
        {
            string str = Request.Form["username"];
            string str2 = Request.Form["email"];
            var member = (from p in db.Members
                          where p.Nickname == str & p.Email == str2
                          select p).ToList();
            if (member.Count() == 0)
            {
                ViewData["error"] = "1";
                return RedirectToAction("findPassword", new { num = 404 });
            }
            else
            {
                foreach (var v in member)
                {
                    string str3 = Request.Form["password"];
                    v.Password = str3;
                    //会员注册时间
                    v.RegisterOn = DateTime.Now;
                    //会员验证码，采用GuID当成验证码属性
                    v.AuthCode = Guid.NewGuid().ToString();
                }
                db.SaveChanges();
                return RedirectToAction("Login");
            }
        }

        //个人信息查看
        public ActionResult UserDetail()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            if (member == null)
            {
                return RedirectToAction("Login");
            }
            else
            {
                return View(member);

            }
        }

        //修改密码
        public ActionResult Editpasswd()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            if (member == null)
            {
                return RedirectToAction("Login");
            }
            return View();
        }

        public ActionResult Editpasswd1()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            string str3 = Request.Form["password"];

            member.Password = str3;
            db.SaveChanges();

            return RedirectToAction("UserDetail");
        }
        //修改收货地址
        public ActionResult Editaddress()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            if (member == null)
            {
                return RedirectToAction("Login");
            }
            return View(member);
        }

        public ActionResult Editaddress1()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            string str3 = Request.Form["address"];
            member.Address = str3;
            db.SaveChanges();

            return RedirectToAction("UserDetail");
        }
        //查看个人订单
        public ActionResult Useroder()
        {
            var member = db.Members.Where(p => p.Email == User.Identity.Name).FirstOrDefault();
            if (member == null)
            {
                return RedirectToAction("Login");
            }
            //var orderlist = db.Orders.Where(o => o.member == member).ToList();
            var orderlist = (from o in db.Orders
                             where o.member.Id == member.Id
                             select o).ToList();
            return View(orderlist);
        }
    }
}

